package cn.edu.stu.syllabus.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.HashMap;

import cn.edu.stu.syllabus.application.SyllabusApplication;

/**
 * Created by daidaijie on 2017/3/26.
 * 储存导航状态的单例类
 */

public class GuideSaver {

    private static final String TAG = "GuideSaver";

    private SharedPreferences mSharedPreferences;

    private SharedPreferences.Editor mEditor;

    private static final String EXTRA_IS_GUIDE_OPEN = "IsGuideOpen";

    private static final String EXTRA_IS_FIRST_OPEN = "IsFirstOpen";

    private HashMap<String, Boolean> mActivityIsGuideMap;

    // 是否开启导航
    private boolean mIsGuideOpen;

    private boolean mIsFirstOpen;

    private GuideSaver() {
        mSharedPreferences = SyllabusApplication.getContext().getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        mActivityIsGuideMap = new HashMap<>();
        mIsGuideOpen = mSharedPreferences.getBoolean(EXTRA_IS_GUIDE_OPEN, true);
        mIsFirstOpen = mSharedPreferences.getBoolean(EXTRA_IS_FIRST_OPEN, true);
    }

    private static class GuideSaverHolder {
        private static GuideSaver sGuideSaver = new GuideSaver();
    }

    public static GuideSaver getInstance() {
        return GuideSaverHolder.sGuideSaver;
    }

    /**
     * 判断某个Activity是否需要导航
     *
     * @param activityName activity的名字
     * @return 该Activity是否需要导航
     */
    public boolean isNeedGuide(String activityName) {
        if (!mIsGuideOpen) {
            return false;
        }

        if (mActivityIsGuideMap.containsKey(activityName)) {
            return mActivityIsGuideMap.get(activityName);
        } else {
            boolean isNeed = mSharedPreferences.getBoolean(activityName, true);
            mActivityIsGuideMap.put(activityName, isNeed);
            return isNeed;
        }
    }

    /**
     * 设置某个Activity已经结束导航
     *
     * @param activityName activity的名字
     */
    public void setFinishGuide(String activityName) {
        mActivityIsGuideMap.put(activityName, false);
        mEditor.putBoolean(activityName, false);
        mEditor.apply();
    }

    /**
     * 设置当前导航是否开启
     *
     * @param guideOpen
     */
    public void setGuideOpen(boolean guideOpen) {
        mIsGuideOpen = guideOpen;
        mEditor.putBoolean(EXTRA_IS_GUIDE_OPEN, guideOpen);
    }

    /**
     * 判断是否第一次打开App
     */
    public boolean isFirstOpenApp() {
        return mIsFirstOpen;
    }

    /**
     * 设置已经打开App
     */
    public void markHaveOpenedApp() {
        mIsFirstOpen = false;
        mEditor.putBoolean(EXTRA_IS_FIRST_OPEN, false);
        mEditor.apply();
    }
}
